package com.woniuxy.redenvelope.util;

import com.woniuxy.redenvelope.service.KillRedEnvelopeSerice;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: Mr·Xiang
 * @create 2024-04-11 14:39
 * 线程池分类
 *  Executors.newFixedThreadPool(10)    固定线程池
 *  Executors.newSingleThreadExecutor() 单线程池，只有一个线程
 *  Executors.newCachedThreadPool()     可变线程池，根据任务的数量自动增加、减少线程池数量
 *  Executors.newScheduledThreadPool(2) 周期线程池，会每隔一段时间执行一次任务
 *  自定义线程池...
 */
@Component
public class RedisKeyExpireUtil {
    @Resource
    private KillRedEnvelopeSerice killRedEnvelopeSerice;

    // 固定线程池：线程池中的线程个数是固定
    private static ExecutorService executors = Executors.newFixedThreadPool(10);

    // 处理向Redis放秒杀信息的方法
    public void addKill(int kid){
        executors.execute(new AddKillRunnable(kid));
    }

    // 移除秒杀信息
    public void removeKill(int kid){
        executors.execute(new RemoveKillRunnable(kid));
    }

    // 添加秒杀任务
    private class AddKillRunnable implements Runnable{
        private int kid;

        public AddKillRunnable(int kid) {
            this.kid = kid;
        }
        @Override
        public void run() {
            // 调用killService方法

            killRedEnvelopeSerice.addKillToRedis(kid);
        }
    }

    // 删除秒杀任务
    private class RemoveKillRunnable implements Runnable{
        private int kid;

        public RemoveKillRunnable(int kid) {
            this.kid = kid;
        }
        @Override
        public void run() {
            // 调用killService方法

            killRedEnvelopeSerice.removeKillFromRedis(kid);
        }
    }
}
